<template>
  <div>
    <BasicModal
      @register="registerModal"
      v-bind="$attrs"
      title="添加通知收件人组"
      :helpMessage="['查看帮助']"
      @ok="okClick"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import { ref } from 'vue';
  import { notificationsParams } from '/@/api/thingsborad/notification/model/notificationsModel';
  import {
    getUserList,
    createTarget,
    getCustomersList,
    getOneCustomerInfo,
    getOneUserInfo,
  } from '/@/api/thingsborad/notification/notification';
  import { createOneTargets } from '../data/notification.data';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';

  let emits = defineEmits(['closeFlag']);
  //用户下拉列表
  let usersListOptions = ref<any>([]);
  //客户下拉列表
  let customerListOptions = ref<any>([]);
  //请求参数
  let params = ref<notificationsParams>({
    pageSize: 50,
    page: 0,
    sortProperty: 'email',
    sortOrder: 'ASC',
  });
  const schemas: FormSchema[] = [
    {
      field: 'ReceivingName',
      required: true,
      component: 'Input',
      label: '收件人名称',

      componentProps: {
        placeholder: '请输入收件人名称',
      },
    },
    {
      field: 'switchType',
      component: 'RadioGroup',
      label: '类型',

      defaultValue: 'PLATFORM_USERS',
      componentProps: {
        options: [
          {
            label: '平台用户',
            value: 'PLATFORM_USERS',
          },
          {
            label: 'Slack',
            value: 'SLACK',
          },
          {
            label: 'Microsoft Teams',
            value: 'MICROSOFT_TEAMS',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        return value.model.switchType === 'SLACK';
      },
      field: 'channelType',
      component: 'RadioGroup',
      label: 'Slack 频道类型',

      defaultValue: 'publicChannel',
      componentProps: {
        options: [
          {
            label: '公开频道',
            value: 'publicChannel',
          },
          {
            label: '私有频道',
            value: 'privateChannel',
          },
          {
            label: '直接消息',
            value: 'directMessage',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        return value.model.switchType === 'SLACK';
      },
      field: 'dialogue',
      component: 'Input',
      required: true,
      label: '对话',

      componentProps: {
        placeholder: '请输入对话内容',
      },
    },
    {
      ifShow: (value) => {
        return value.model.switchType === 'MICROSOFT_TEAMS';
      },
      field: 'webhookURL',
      component: 'Input',
      required: true,
      label: 'WebhookURL',

      componentProps: {
        placeholder: '请输入Webhook URL',
      },
    },
    {
      ifShow: (value) => {
        return value.model.switchType === 'MICROSOFT_TEAMS';
      },
      field: 'channelName',
      component: 'Input',
      required: true,
      label: 'ChannelName',

      componentProps: {
        placeholder: '请输入Channel Name',
      },
    },
    {
      ifShow: (value) => {
        return value.model.switchType === 'PLATFORM_USERS';
      },
      field: 'userFilter',
      component: 'Select',
      label: '用户筛选器',

      defaultValue: 'ALL_USERS',
      required: true,
      componentProps: {
        options: [
          {
            label: '所有用户',
            value: 'ALL_USERS',
          },
          {
            label: '租户管理员',
            value: 'TENANT_ADMINISTRATORS',
          },
          {
            label: '客户用户',
            value: 'CUSTOMER_USERS',
          },
          {
            label: '用户列表',
            value: 'USER_LIST',
          },
          {
            label: '实体所有者的用户',
            value: 'ORIGINATOR_ENTITY_OWNER_USERS',
          },
          {
            label: '受影响的用户',
            value: 'AFFECTED_USER',
          },
        ],
      },
    },
    {
      ifShow: (value) => {
        return (
          value.model.switchType === 'PLATFORM_USERS' && value.model.userFilter === 'USER_LIST'
        );
      },
      field: 'usersList',
      component: 'Select',
      label: '用户列表',

      required: true,
    },
    {
      ifShow: (value) => {
        return (
          value.model.switchType === 'PLATFORM_USERS' && value.model.userFilter === 'CUSTOMER_USERS'
        );
      },
      field: 'customerUsers',
      component: 'Select',
      label: '客户',

      required: true,
    },
    {
      field: 'describe',
      component: 'Input',
      label: '描述',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '请输入描述信息',
        style: {
          height: '55px',
        },
      },
    },
  ];
  // 表格初始化
  const [registerForm, { updateSchema, validate, resetFields, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  // 获取用户下拉列表数据
  async function getUsersListSelect(params: notificationsParams) {
    usersListOptions.value = [];
    try {
      const userData = await getUserList(params);
      userData.data.forEach((item) => {
        let dome = {
          value: item.id.id,
          label: item.name,
        };
        usersListOptions.value.push(dome);
      });
    } catch (error) {
      console.error('获取数据时出错：', error);
      // 处理错误情况
    }
  }
  //获取客户下拉列表数据
  async function getCustomerListSelect(params: notificationsParams) {
    customerListOptions.value = [];
    try {
      const customerData = await getCustomersList(params);
      customerData.data.forEach((item) => {
        let dome = {
          value: item.id.id,
          label: item.name,
        };
        customerListOptions.value.push(dome);
      });
    } catch (error) {
      console.error('获取数据时出错：', error);
      // 处理错误情况
    }
  }
  //用户客户下拉表单数据填充更新
  const [registerModal, { closeModal, setModalProps }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({
      okText: '保存',
      width: 800,
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
    if (data !== true) {
      if (data.type === 'Microsoft Teams') {
        setFieldsValue({
          ReceivingName: data.name,
          switchType: 'MICROSOFT_TEAMS',
          webhookURL: data.info.configuration.webhookUrl,
          channelName: data.info.configuration.channelName,
          describe: data.description,
        });
      } else if (data.type === '平台用户') {
        setFieldsValue({
          ReceivingName: data.name,
          switchType: 'PLATFORM_USERS',
          userFilter: data.info.configuration.usersFilter.type,
          describe: data.description,
        });
        if (data.info.configuration.usersFilter.type === 'CUSTOMER_USERS') {
          try {
            let oneCustomerInfo = await getOneCustomerInfo(
              data.info.configuration.usersFilter.customerId,
            );
            setFieldsValue({
              customerUsers: oneCustomerInfo.title,
            });
          } catch (error) {}
        }

        if (data.info.configuration.usersFilter.type === 'USER_LIST') {
          try {
            let usersFilterList: any = [];
            data.info.configuration.usersFilter.usersIds.forEach(async (id) => {
              let oneUserInfo = await getOneUserInfo(id);
              usersFilterList.push(oneUserInfo.email);
            });

            setFieldsValue({
              usersList: usersFilterList,
            });
          } catch (error) {}
        }
      } else {
        setFieldsValue({
          ReceivingName: data.name,
          switchType: 'SLACK',
          describe: data.description,
        });
      }
    }
    params.value.sortProperty = 'email';
    await getUsersListSelect(params.value);
    await updateSchema({
      field: 'usersList',
      componentProps: {
        mode: 'multiple',
        options: usersListOptions.value,
      },
    });
    params.value.sortProperty = 'title';
    await getCustomerListSelect(params.value);
    await updateSchema({
      field: 'customerUsers',
      componentProps: {
        mode: 'multiple',
        options: customerListOptions.value,
      },
    });
  });
  //创建收件人确实点击事件
  async function okClick() {
    const formData = await validate();
    let createTargetsParams: createOneTargets = {
      name: formData.ReceivingName,
      configuration: {
        type: formData.switchType,
        description: formData.describe,
      },
    };
    if (formData.switchType === 'PLATFORM_USERS') {
      createTargetsParams.configuration.usersFilter = { type: formData.userFilter };
      if (formData.userFilter === 'USER_LIST') {
        createTargetsParams.configuration.usersFilter = {
          type: formData.userFilter,
          usersIds: formData.usersList,
        };
      } else if (formData.userFilter === 'CUSTOMER_USERS') {
        createTargetsParams.configuration.usersFilter = {
          type: formData.userFilter,
          customerId: formData.customerUsers[0],
        };
      }
    } else if (formData.switchType === 'MICROSOFT_TEAMS') {
      createTargetsParams.configuration.webhookUrl = formData.webhookURL;
      createTargetsParams.configuration.channelName = formData.channelName;
    }
    await createTarget(createTargetsParams);
    await resetFields();
    emits('closeFlag', true);
    closeModal();
  }
</script>
